package cn.qidd.keep.common.controller.file;

import cn.qidd.keep.common.model.UploadFile;
import cn.qidd.keep.common.service.file.FileService;
import cn.qidd.keep.domain.core.Constants;
import cn.qidd.keep.domain.core.Result;
import cn.qidd.keep.domain.web.BaseController;
import cn.qidd.keep.domain.web.UserVO;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * Created by sunyanping on 2018/10/11
 */
@RestController
@RequestMapping("/api/file")
@Api(description = "文件管理")
public class FileController extends BaseController {

    @Autowired
    private FileService fileService;
    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private GridFSBucket gridFSBucket;

    @PostMapping("/upload")
    @ApiOperation(value = "单个文件上传", notes = "单个文件上传")
    public Result<UploadFile> upload(@ApiIgnore @RequestHeader(Constants.TOKEN) String token,
                         @RequestParam("file") MultipartFile file) throws IOException {
        UserVO userVO = getUserByToken(token);
        if (file == null) {
            return new Result<>(Result.Status.FAILURE, "请选择文件");
        }
        UploadFile upload = fileService.upload(userVO, file);
        return new Result<>(Result.Status.SUCCESS, "上传成功" ,upload);
    }

    @GetMapping("/download/{id}")
    @ApiOperation(value = "文件下载", notes = "文件下载")
    public ResponseEntity<Object> download(@PathVariable("id") String id) throws IOException {
        Query query = Query.query(Criteria.where("_id").is(id));
        GridFSFile gridFSFile = gridFsTemplate.findOne(query);

        if (gridFSFile == null) {
            return ResponseEntity.ok().body(null);
        }
        String filename = URLEncoder.encode(gridFSFile.getFilename(), "UTF-8");
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        InputStream inputStream = gridFsResource.getInputStream();
        return ResponseEntity
                .ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=\"" + filename + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
                .header("Connection", "close")
                .body(getBytes(inputStream));
    }

    private byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int  i = 0;
        while (-1!=(i=inputStream.read(b))){
            bos.write(b,0,i);
        }
        return bos.toByteArray();
    }
}
